package com.soar.recruitment.common.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.soar.recruitment.common.app.SOARBaseApplication;

public class DeviceUniqueFactory {

    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";
    private String mUniqueId = "";

    public static volatile DeviceUniqueFactory instance;

    public static DeviceUniqueFactory getInstance() {
        if (instance == null) {
            synchronized (DeviceUniqueFactory.class) {
                if (instance == null) {
                    instance = new DeviceUniqueFactory();
                }
            }
        }
        return instance;
    }

    public DeviceUniqueFactory() {
        if(TextUtils.isEmpty(mUniqueId)) {
            synchronized (DeviceUniqueFactory.class) {
                initUniqueId();
            }
        }
    }

    private String initUniqueId() {
        if(TextUtils.isEmpty(mUniqueId)) {
            final SharedPreferences prefs = SOARBaseApplication.getInstance().getSharedPreferences(PREFS_FILE, 0);
            final String id = prefs.getString(PREFS_DEVICE_ID, "");

            if (!TextUtils.isEmpty(id)) {
                mUniqueId = id;
            } else {
                final String androidId = Settings.Secure.getString(SOARBaseApplication.getInstance().getContentResolver(), Settings.Secure.ANDROID_ID);
                if (!TextUtils.isEmpty(androidId) && !"9774d56d682e549c".equals(androidId)) {
                    mUniqueId = androidId;
                } else {
                    try {
                        final String deviceId = ((TelephonyManager) SOARBaseApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                        if (!TextUtils.isEmpty(deviceId)) {
                            mUniqueId = deviceId;
                        } else {
                            mUniqueId = "";
                        }
                    } catch (Exception e) {
                        mUniqueId = "";
                    }
                }
                prefs.edit().putString(PREFS_DEVICE_ID, mUniqueId).commit();
            }
        }
        return mUniqueId;
    }

    public String getUniqueId() {
        if(!TextUtils.isEmpty(mUniqueId)) {
            return mUniqueId;
        } else {
            return initUniqueId();
        }
    }

}
